package com.wxg.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class UploadController {

    @GetMapping("/")
    public String index() {
        return "upload";
    }

    /**
     * 从网上抄的代码: https://www.jianshu.com/p/0d87a582aac4
     * 再次震惊Java代码的臃肿
     *
     * @param srcFile
     * @param redirectAttributes
     * @return
     */
    @PostMapping("upload")
    public String fileUpload(@RequestParam("file") MultipartFile srcFile,
                             RedirectAttributes redirectAttributes) {
        if (srcFile.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择一个文件");
            return "redirect:upload_status";
        }

        try {
            File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!destFile.exists()) {
                destFile = new File("");
            }
            System.out.println(String.format("file path: %s", destFile.getAbsolutePath()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String times = sdf.format(new Date());
            File upload = new File(destFile.getAbsolutePath(), "picture/" + times);
            if (!upload.exists()) {
                upload.mkdirs();
            }
            System.out.println(String.format("完整的上传路径：%s/%s", upload.getAbsolutePath(), srcFile));
            byte[] bytes = srcFile.getBytes();

            Path path = Paths.get(String.format("%s/%s",
                    upload.getAbsolutePath(), srcFile.getOriginalFilename()));
            Files.write(path, bytes);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String originalFilename = srcFile.getOriginalFilename();
            String suffixName =
                    originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            String newFileName = String.format("%s.%s", uuid, suffixName);
            redirectAttributes.addFlashAttribute("message",
                    String.format("%s%s", "文件上传成功", newFileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:upload_status";
    }

    @GetMapping("upload_status")
    public String uploadStatusPage() {
        return "upload_status";
    }
}
